package public

import (
	"context"
	"errors"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"
	"server/vars"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.TokenResp, err error) {
	user := &models.User{
		Username: req.Username,
	}
	if !utils.GetData(user) {
		return nil, errors.New("用户名或密码错误")
	}
	// if user.Password != utils.MD5(req.Password+user.Salt) {
	if user.Password != utils.MD5(utils.MD5(req.Password)+user.Salt) {
		return nil, errors.New("用户名或密码错误")
	}

	jwtUser := utils.JwtUser{
		Id:       user.ID,
		Username: user.Username,
		Mobile:   user.Mobile,
		Email:    user.Email,
	}
	token, _ := utils.GetJwtToken(l.svcCtx.Config.Auth.AccessSecret, jwtUser)
	resp = &types.TokenResp{
		UserId:   user.ID,
		Username: user.Username,
		Token:    token,
	}

	userKey := vars.UserIdPrefix + utils.UintToString(user.ID)
	value := utils.GetString(userKey)
	if value != "" {
		utils.DelCache(vars.UserTokenPrefix + value)
	}
	utils.DelCache(userKey)

	//把token存入redis
	utils.SetString(vars.UserTokenPrefix+token, utils.StructToJson(jwtUser))
	utils.SetStringEx(vars.UserIdPrefix+utils.Int64ToString(int64(jwtUser.Id)), token)

	return resp, nil
}
